package com.pms.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pms.controller.BaseController;
import com.pms.entity.BaseModel;
import com.pms.entity.IotAgency;
import com.pms.entity.IotWaterPumpGroup;
import com.pms.exception.R;
import com.pms.service.IIotAgencyService;
import com.pms.service.IIotWaterPumpGroupService;
import com.pms.service.IWoGiaWpAttrService;
import com.pms.util.httpUtil.HttpClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created by hm on 2018/9/3.
 */
@RestController
@RequestMapping("/iot/wojiaRead")
@Api(value="查询沃佳数据",description = "查询沃佳数据")
public class ApiIotTestController extends BaseController {
    @Autowired
    IWoGiaWpAttrService woGiaWpAttrService;
    @Autowired
    IIotAgencyService agencyService;
    @Autowired
    IIotWaterPumpGroupService waterPumpGroupService;
    /**
     * 添加woGia 小区
     * @return
     */
    @PostMapping("/addWoGiaCommunity")
    @ApiOperation(value = "自动生成 沃佳 小区数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name="companyCode",value="公司编号",required = true,dataType = "String",paramType="form")
    })
    public R addWoGiaCommunity(String companyCode){
        Map<String,String> sqlMap = new HashMap<String,String>();
        sqlMap.put("columnStr","*");
        sqlMap.put("tablename","wogia.t_project");
        List<Map<String,Object>> woGiaCommunityMap =woGiaWpAttrService.selectAttrByTablenameAndColumn(sqlMap);
        if(StringUtils.isBlank(companyCode)){
            companyCode ="048159";
        }
        List<IotAgency> insertAgencyList = new ArrayList<IotAgency>();

        IotAgency agency =agencyService.selectOne(new EntityWrapper<IotAgency>().eq("agency_level",2).eq("company_code",companyCode));
        if(agency==null){
            agency = new IotAgency();
            agency.setId(BaseModel.returnStaticIdLong());
            agency.setCompanyCode(companyCode);
            agency.setLevel(2);
            agency.setParentName("系统");
            agency.setParentId(-1L);
            agency.setName("沃佳物业");
            agency.setLinkName("蒲天波");
            agency.setLinkPhone("13208183131");
            agency.setCode("wogia_wy");
            agency.setStatus(1);
            agency.setCreateBy("62067870928897");
            agency.setCreateTime(new Date());
            insertAgencyList.add(agency);
        }
        String gd_lbsUrl ="https://restapi.amap.com/v3/place/text";
        String gd_paramStr ="s=rsv3&children=&key=8325164e247e15eea68b59e89200988b&page=1&offset=10&city=510100&language=zh_cn&callback=jsonp_728932_&platform=JS&logversion=2.0&sdkversion=1.3&appname=https://lbs.amap.com/console/show/picker&csid=5D7BD18B-8B25-44B2-BF44-852909E92C1B&keywords=";
       Date date =new Date();
        for(Map<String,Object> map : woGiaCommunityMap){
            IotAgency insertAgency = new IotAgency();
            insertAgency.setId(BaseModel.returnStaticIdLong());
            insertAgency.setCompanyCode(companyCode);
            insertAgency.setLevel(3);
            insertAgency.setParentName(agency.getName());
            insertAgency.setParentId(agency.getId());
            insertAgency.setAgencyAddress( (String) map.get("project_address") );
            insertAgency.setAreaGb( (Integer) map.get("city_id") );
            insertAgency.setName( (String) map.get("project_name") );
            insertAgency.setCityGb( Integer.parseInt(insertAgency.getAreaGb().toString().substring(0,4)+"00") );
            insertAgency.setProvinceGb(Integer.parseInt(insertAgency.getAreaGb().toString().substring(0,2)+"0000") );
            insertAgency.setLinkName(agency.getLinkName());
            insertAgency.setLinkPhone(agency.getLinkPhone());
            String addressKeyWords =(String) map.get("project_address");
            addressKeyWords = addressKeyWords==null?"":addressKeyWords;
            String result = HttpClientUtil.doGet(gd_lbsUrl,gd_paramStr+addressKeyWords);
            result = result.substring(result.indexOf("{"),result.lastIndexOf("}")+1);
            JSONObject resultJson = JSONObject.parseObject(result);
            JSONArray poiArray = resultJson.getJSONArray("pois");
            JSONObject poiJson = poiArray.getJSONObject(0);
            String poiLocation =  poiJson.getString("location");
            String[] locationArr = poiLocation.split(",");
            insertAgency.setLatitude(Double.parseDouble(locationArr[1]));
            insertAgency.setLongitude(Double.parseDouble(locationArr[0]));
            insertAgency.setCode("wogia_"+map.get("id"));
            insertAgency.setStatus(1);
            insertAgency.setCreateBy("62067870928897");
            insertAgency.setCreateTime(date);
            insertAgencyList.add(insertAgency);
            // 水泵房
            IotAgency insertHouseAgency = new IotAgency();
            insertHouseAgency.setId(BaseModel.returnStaticIdLong());
            insertHouseAgency.setCompanyCode(companyCode);
            insertHouseAgency.setLevel(4);
            insertHouseAgency.setParentName(insertAgency.getName());
            insertHouseAgency.setParentId(insertAgency.getId());
            insertHouseAgency.setName("一号水泵房");
            insertHouseAgency.setAreaGb( insertAgency.getAreaGb());
            insertHouseAgency.setCityGb( insertAgency.getCityGb());
            insertHouseAgency.setProvinceGb( insertAgency.getProvinceGb() );
            insertHouseAgency.setLinkName(insertAgency.getLinkName());
            insertHouseAgency.setLinkPhone(insertAgency.getLinkPhone());
            insertHouseAgency.setAgencyAddress( insertAgency.getAgencyAddress());
            insertHouseAgency.setLatitude(insertAgency.getLatitude()+(0.0002d));
            insertHouseAgency.setLongitude(insertAgency.getLongitude()-(0.0002d));
            insertHouseAgency.setCode("wogia_"+map.get("id")+"_01");
            insertHouseAgency.setStatus(1);
            insertHouseAgency.setCreateBy("62067870928897");
            insertHouseAgency.setCreateTime(date);
            insertAgencyList.add(insertHouseAgency);
    }
        agencyService.insertBatch(insertAgencyList);
        return R.ok().put("data",woGiaCommunityMap);
    }

    /**
     * 添加woGia 小区
     * @return
     */
    @PostMapping("/addWoGiaWpDevice")
    @ApiOperation(value = "自动生成 沃佳 水泵设备组数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name="companyCode",value="公司编号",required = true,dataType = "String",paramType="form")
    })
    public R addWoGiaWpDevice(String companyCode){
        if(StringUtils.isBlank(companyCode)){
            companyCode ="04815967";
        }
        Date date = new Date();
        Map<String,String> sqlMap = new HashMap<String,String>();
        sqlMap.put("columnStr","*");
        sqlMap.put("tablename","wogia.t_device");
        //查询wogia 设备组 数据
        List<Map<String,Object>> woGiaDeviceMap =woGiaWpAttrService.selectAttrByTablenameAndColumn(sqlMap);
        List<IotWaterPumpGroup> wpList = new ArrayList<IotWaterPumpGroup>();
        for(Map<String,Object> map:woGiaDeviceMap){
            IotWaterPumpGroup wp = new IotWaterPumpGroup();
            wp.setId(BaseModel.returnStaticIdLong());
            wp.setName((String)map.get("device_name"));
            wp.setCode((String)map.get("table_device"));
            IotAgency house = agencyService.selectOne(new EntityWrapper<IotAgency>().eq("agency_code","wogia_"+map.get("project_id")+"_01").eq("company_code",companyCode));
            wp.setCommunityName(house.getParentName());
            wp.setCommunityId(house.getParentId());
            wp.setDataType(1);// 有线网络
            wp.setDataSource(2);// 数据从沃佳查询
            wp.setLinkName(house.getLinkName());
            wp.setLinkPhone(house.getLinkPhone());
            wp.setCompanyCode(companyCode);
            wp.setLevel(house.getLevel()+1);
            wp.setCreateBy("62067870928897");
            wp.setCreateTime(date);
            wp.setParentId(house.getId());
            wp.setParentName(house.getName());
            wpList.add(wp);
        }
        waterPumpGroupService.insertBatch(wpList);
        return R.ok().put("data",woGiaDeviceMap);
    }



    /**
     * 添加woGia 小区
     * @return
     */
    @PostMapping("/generateWoGiaPumpNumRecord")
    @ApiOperation(value = "自动生成 沃佳 水泵设备组 小泵数量")
    @ApiImplicitParams({
    })
    public R generateWoGiaPumpNumRecord(){
        waterPumpGroupService.generateWoGiaPumpNumRecord();
        return R.ok();
    }

}
